#!/bin/bash

detect_package_manager() {
    if command -v apt &> /dev/null; then
        echo "apt"
        elif command -v yum &> /dev/null; then
        echo "yum"
    else
        echo "none"
    fi
}
package_manager=$(detect_package_manager)
echo -e "\033[32m正在检查并安装 wget 、git 、 unrar 和 openjdk-17-jdk ...\033[0m"
# 开始安装依赖
# 检查 sudo 命令是否存在，如果不存在则安装它
if ! command -v sudo &> /dev/null; then
    echo -e "\033[31msudo 命令不存在，正在安装 sudo...\033[0m"
    package_manager=$(detect_package_manager)
    if [ "$package_manager" = "none" ]; then
        echo -e "\033[31m仅适配了 apt 或 yum 包管理器的系统，无法继续安装。\033[0m"
        exit 1
    fi
    if [ "$package_manager" = "apt" ]; then
        apt update && apt install -y sudo
    elif [ "$package_manager" = "yum" ]; then
        yum install -q -y sudo
    fi
    echo -e "\033[32msudo 安装完成。\033[0m"
else
    echo -e "\033[32msudo 存在继续安装过程。\033[0m"
fi

if [ "$package_manager" = "apt" ];then
    sudo apt update && sudo DEBIAN_FRONTEND=noninteractive apt install -qq -y libgbm1  libgtk-3-0 libnotify4 libxss1 libxtst6 xdg-utils libatspi2.0-0 libsecret-1-0 wget unrar screen git openjdk-17-jdk unzip ffmpeg dialog tmux jq curl
else
    sudo yum install -q -y epel-release wget  screen git java-17-openjdk java-17-openjdk-devel unzip xdg-utils mesa-libgbm alsa-lib gtk3 libnotify libXScrnSaver libXtst at-spi2-core libsecret ffmpeg dialog tmux libgbm
fi

if [ "$package_manager" = "apt" ];then
    sudo apt update && sudo apt install -y tmux wget unrar unzip curl libgbm1  zip  jq  xvfb libnss3 bzip2 whiptail
    sudo apt remove linuxqq
    sudo apt install -y libasound2
    sudo apt install -y libgconf-2-4
    sudo apt install -y libasound2t64
else
    sudo yum install -q -y tmux wget unzip curl libgbm alsa-lib-devel nss dbus-libs at-spi2-atk gtk3 cups-libs zip unzip jq  xvfb bzip2 whiptail
fi

wget https://gitee.com/laixi_lingdun/Manyana_deploy/raw/main/ntqq.sh -O ntqq.sh
chmod +x ntqq.sh

echo -e "\033[32mNTQQ即将开始安装\033[0m"
echo -e "\033[32m在即将弹出的界面中建议使用\033[0m \033[33m！！Shell安装！！\033[0m"
echo -e "\033[32m在即将弹出的界面中建议使用\033[0m \033[33m！！Shell安装！！\033[0m"
echo -e "\033[32m不需要安装额外拓展，安装好后退出选择退出界面即可\033[0m"
echo -e "\033[32m不需要安装额外拓展，安装好后退出选择退出界面即可\033[0m"
sleep 4
sudo bash ntqq.sh

echo -e "\033[32m将使用tmux运行安装过程，防止ssh断开或者意外原因导致安装中断\033[0m"
echo -e "\033[32m如果ssh意外断开了，安装过程仍然在进行，使用cat install_log.txt手动查看安装进度\033[0m"
echo -e "\033[32m安装过程的日志保存到了install_log.txt\033[0m"
sleep 4
# 确保安装脚本具有执行权限
wget https://gitee.com/laixi_lingdun/Manyana_deploy/raw/main/install_payload.sh -O install_program.sh
chmod +x install_program.sh



# 使用 tmux 运行安装脚本并重定向输出到日志文件
tmux new-session -s install 'export LANG=en_US.UTF-8; ./install_program.sh | tee install_log.txt'
echo -e "\033[32m安装过程的日志保存到了install_log.txt,你可以执行cat install_log.txt来查看是否成功。\033[0m"
sleep 2
cat install_log.txt